// pages/plaza/plaza.js
const app=App()
var openid=wx.getStorageSync('openid')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    credit:''
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: async function (){
   this.refreshCredit()
   let db=await wx.cloud.callFunction({
    name:'getClientData'
  })
      let firstday = (new Date(db.result.data[0].time)).getDate()
      let firstmonth = (new Date(db.result.data[0].time)).getMonth()
      let nowday = (new Date().getDate())
      let nowmonth = (new Date().getMonth())
   this.ifClientNew(firstday,nowday,firstmonth,nowmonth)
  },
  tapGetCredit(){
    let cre=0;
    let time='';
    let miniCredit=Math.floor(Math.random()*3)+1;
    wx.cloud.callFunction({name:"getClientData",})
    .then(res=>{cre=res.result.data[0].credit;
                time=res.result.data[0].time;})
    .then(()=>{ wx.cloud.callFunction
                ({ name:"creditUpdate",
                  data:{time:time,
                        cre:cre,
                        quantity:miniCredit,
                        reason:'点击广场页屏幕随机获取'} 
                }) 
              }) 
    .then(()=>{this.refreshCredit()})
  },
  refreshCredit(){
  wx.cloud.callFunction({
    name:'getClientData'
  })
  .then(res=>{
    var credit=res.result.data[0].credit
    this.setData({
      credit:credit
    })
  })
 },
  async ifClientNew(firstday,nowday,firstmonth,nowmonth){
     if((firstday!=nowday)||(firstmonth!=nowmonth))
      {
        let cre=0
        wx.cloud.callFunction({name:"getClientData",})
        .then(res=>{cre=res.result.data[0].credit})
        .then(()=>{ wx.cloud.callFunction
                    ({ name:"creditUpdate",
                      data:{time:+new Date(),
                            cre:cre,
                            quantity:50,
                            reason:'每日广场页获取'} 
                    }) 
                  })  
      }
 },
 onShow: function () {
  this.refreshCredit()
}
})
